using System;
using DevExpress.XtraEditors;

namespace DBTractores
{
    public partial class ProcessingXtraForm: XtraForm
    {
        private DateTime _previousTime;

        #region Properties

        public IProgressWorker ProgressWorker { get; set; }

        #endregion

        public ProcessingXtraForm()
        {
            InitializeComponent();
        }

        #region Event Handlers

        private void ProcessingXtraForm_Load(object sender, EventArgs e)
        {            
            progressBarControl.Properties.Step = 1;
            ProgressWorker.DocumentProcessing += DocumentProcessing;
            backgroundWorker.RunWorkerAsync();
        }

        private void DocumentProcessing(object sender, EventArgs e)
        {
            if ((DateTime.Now - _previousTime).Milliseconds <= 100)
                return;
            _previousTime = DateTime.Now;
            backgroundWorker.ReportProgress(0);
        }

        private void backgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            _previousTime = DateTime.Now;
            ProgressWorker.Work();
        }

        private void backgroundWorker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            ProgressWorker.DocumentProcessing -= DocumentProcessing;
            Close();
        }

        private void backgroundWorker_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
        {
            progressBarControl.Properties.Maximum = ProgressWorker.DocumentCount;
            progressBarControl.Position = ProgressWorker.DocumentIndex;
            progressBarControl.PerformStep();
            processingLabelControl.Text = "Processando documento " + ProgressWorker.DocumentNumber + " (" + ProgressWorker.DocumentIndex + "/" + ProgressWorker.DocumentCount + ")";
        }

        #endregion        
    }
}